#include <DHT.h>
#include <DHT_U.h>
#include <Arduino.h>
#include "sensor_manager.h"
#include "mqtt_manager.h"

#define DHTPIN 4
#define DHTTYPE DHT22

DHT_Unified dht(DHTPIN, DHTTYPE);

float temperature;
float humidity;

 // 全局变量或类成员，记录上次发送时间（毫秒）
unsigned long lastSendTime = 0;

void sensorInit() {
  dht.begin();
  Serial.println(F("-----------------DHT22初始化成功-----------------"));
  // 给温度放一个传感器对象
  sensor_t sensor;
  dht.temperature().getSensor(&sensor);
  Serial.println(F("------------------------------------"));
  Serial.println(F("温度传感器"));
  Serial.print  (F("传感器类型: ")); Serial.println(sensor.name);
  Serial.print  (F("传感器版本:  ")); Serial.println(sensor.version);
  Serial.print  (F("传感器id:   ")); Serial.println(sensor.sensor_id);
  Serial.print  (F("最高温度:   ")); Serial.print(sensor.max_value); Serial.println(F("°C"));
  Serial.print  (F("最低温度:   ")); Serial.print(sensor.min_value); Serial.println(F("°C"));
  Serial.print  (F("误差:  ")); Serial.print(sensor.resolution); Serial.println(F("°C"));
  Serial.println(F("------------------------------------"));

  // 给湿度放一个传感器对象
  dht.humidity().getSensor(&sensor);
  Serial.println(F("湿度传感器"));
  Serial.print  (F("传感器类型: ")); Serial.println(sensor.name);
  Serial.print  (F("传感器版本:  ")); Serial.println(sensor.version);
  Serial.print  (F("传感器id:   ")); Serial.println(sensor.sensor_id);
  Serial.print  (F("最高湿度:   ")); Serial.print(sensor.max_value); Serial.println(F("%"));
  Serial.print  (F("最低湿度:   ")); Serial.print(sensor.min_value); Serial.println(F("%"));
  Serial.print  (F("误差:  ")); Serial.print(sensor.resolution); Serial.println(F("%"));
  Serial.println(F("------------------------------------"));
}

void dataPush() {
  unsigned long now = millis();
  // 已经关闭发送，或者上一次发送不到2S，取消发送
  if (!isSend || now - lastSendTime <= 2000 || !HAMQTT.connected()) {
    return;
  }

  // 记录最后一次发送时间
  lastSendTime = now;

  // 创建事件，温度事件
  sensors_event_t event;
  dht.temperature().getEvent(&event);
  bool tempIsNan = isnan(event.temperature);
  if (tempIsNan) {
    Serial.println(F("读取温度错误!"));
  } else {
    temperature = event.temperature;
  }

  // 创建事件，湿度事件
  dht.humidity().getEvent(&event);
  bool humIsNan = isnan(event.relative_humidity);
  if (humIsNan) {
    Serial.println(F("读取湿度错误!"));
  } else {
    humidity = event.relative_humidity;
  }
  Serial.print(F("温度: ======>"));Serial.println(temperature);
  Serial.print(F("湿度: ======>"));Serial.println(humidity);
  if (!tempIsNan && !humIsNan) {
    // 读取到了数据就是绿色，持续50ms
    rgbLedWrite(RGB_BUILTIN,0,RGB_BRIGHTNESS,0);
    delay(50);
    // 然后关闭灯光
    digitalWrite(RGB_BUILTIN, LOW);  
    // 数据传到MQTT
    ha_sensor_temp_c -> setState(temperature);
    ha_sensor_humidity -> setState(humidity);
  }
}
